import libxml2
import libxslt
import difflib

classType = 'enum'
classXPath = '/iConnect/Enumerations/%s'%classType

outDir = '../../csharp/iConnect'

def generateCode(xml, style, package, className, fileExt):
    fileCode = '%s/%s/%s%s'%(outDir, package, className, fileExt)
    codeCur = []
    try:
        fi = file(fileCode, 'r')
        codeCur = fi.read().splitlines()
        fi.close()
    except:
        print "*** Could not open current ", fileCode
    #
    xmlParm = dict(generate="""'%s'"""%className)
    result = style.applyStylesheet(xml, xmlParm)
    #
    if result:
        codeNew = style.saveResultToString(result).splitlines()
        bDiff = False
        for line in difflib.ndiff(codeCur, codeNew):
            if line[0] != ' ':
                print line
                bDiff = True
        if bDiff:
            try:
                fo = file(fileCode, 'w')
                print >> fo, '\n'.join(codeNew)
                fo.close()
            except:
                print "ERR Could not open output ", fileCode
        result.freeDoc()

if __name__ == '__main__':

    # Xml source
    xml = libxml2.parseFile('../../codegen/xml/iConnect.xml')
    ctxt = xml.xpathNewContext()
    ctxt.xpathRegisterNs('xml', 'http://www.w3.org/2001/XMLSchema-instance')
    
    # csharp style sheet
    ss_csharp = libxml2.parseFile('../../codegen/xml/csharp_%s.xsl'%(classType))
    style_csharp = libxslt.parseStylesheetDoc(ss_csharp)

    xpath = "%s/@name"%(classXPath)
    clist = ctxt.xpathEval(xpath)
    genClasses = [x.getContent() for x in clist]
    for className in genClasses:
        #xpath = "%s[@name='%s']/@package"%(classXPath,className)
        #attr = ctxt.xpathEval(xpath)
        #package = attr and attr[0].getContent() or 'iCMsg'
        package = ''
        print className, package
        for style, fileExt in [(style_csharp, '.cs')]:
            generateCode(xml, style, package, className, fileExt)

    # Style sheet release
    style_csharp.freeStylesheet()

    # Xml source release
    ctxt.xpathRegisteredNsCleanup()
    ctxt.xpathFreeContext()
    xml.freeDoc()
